/**
 * Shader implementation
 */

#include "Shader.h"
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

/////////////////////////////////////////////////

Shader::Shader(const std::string& path, GLenum type) : _name(path)
{
	// TODO make C++...instead of this easy C!
	
	FILE *fp;
	char *content = NULL;
	int fd, count;
	fd = open(path.c_str(), O_RDONLY);
	assert(fd);
	count = lseek(fd,0,SEEK_END);
	close(fd);
	content = (char *)calloc(1,(count+1));
	fp = fopen(path.c_str(),"r");
	count = fread(content,sizeof(char),count,fp);
	content[count] = '\0';
	fclose(fp);

	createShader(content, type);
	free(content);

}

/////////////////////////////////////////////////

Shader::Shader(const std::string& name, const char* content, GLenum type) : _name(name)
{
	assert(content != 0);
	createShader(content, type);
}

/////////////////////////////////////////////////

void Shader::createShader(const char* content, GLenum type)
{
	assert(type == GL_FRAGMENT_SHADER || type == GL_VERTEX_SHADER);
	_glName = glCreateShader(type);
	glShaderSource(_glName,1,(const char **)&content,NULL);
	glCompileShader(_glName);

	int compiled;
	glGetShaderiv(_glName, GL_COMPILE_STATUS, &compiled);

	if (!compiled) {
		int logsize, written;
		char* logptr;
		glGetShaderiv(_glName, GL_INFO_LOG_LENGTH, &logsize);
		logptr = (char *)(calloc(1,logsize));
		glGetShaderInfoLog(_glName, logsize, &written, logptr);
		std::cerr << _name << " did not compile!" << std::endl;
		std::cerr << logptr << std::endl;
		free(logptr);
		exit(1);
	}

	checkGLError();
}

